package woa.tree.binary;

/**
 * 二叉树的最大深度
 *
 * @author wangpeng
 * @date 2021/12/3
 */
public class MaxDepth {

    static int maxDepth = 0;

    public static int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        up2down(root, 1);
        return maxDepth;
    }

    /**
     * 自上而下
     *
     * @param root
     * @param depth
     */
    public static void up2down(TreeNode root, int depth) {
        if (root.left == null && root.right == null) {
            maxDepth = Math.max(maxDepth, depth);
            return;
        }
        if (root.left != null) {
            up2down(root.left, depth + 1);
        }
        if (root.right != null) {
            up2down(root.right, depth + 1);
        }
    }

    /**
     * 自下而上
     *
     * @param root
     * @return
     */
    public static int down2up(TreeNode root) {
        if (root == null) {
            return 0;
        }

        return Math.max(down2up(root.left), down2up(root.right)) + 1;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        System.out.println(down2up(root));
    }
}
